<!--
* description: 质量活动维护-质量活动车辆
* author: wangjuan
* createdDate: 2021-07-19
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-components="tableComponents"
      :dynamic-buttons="tableButtons"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-table-defult-height="tableHeight"
      :callback-obj="callbackObj"
      :is-show-pagination="false"
    />
    <!-- 车辆选择 -->
    <carSelect
      :key="editPopupsKey0"
      :dynamic-edit-row-data="carEditRowData"
      :popups-visible-car="popupsVisibleCar"
      @close="close0"
      @returnCarData="returnCarData"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/se/serviceActivities'
import { exportExcel } from '@/utils/getTimeString.js'

export default {
  name: 'QualityActivityCar',

  components: {
    OneTableTemplate,
    carSelect: () => import('./component/carSelect.vue')

  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  props: {
    dataForForm: {
      type: Object,
      default: () => {}
    }
  },

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      // apiConfig: api.queryQualityActivityInfoCar,
      tableHeight: 300,
      editPopupsKey0: 'editPopupsKey0',
      carEditRowData: {},
      popupsVisibleCar: false,
      carDatas: [],
      selectCar: [],

      // 按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'add',
          clickEvent: () => this.carAdd(),
          text: this.$t('sys.button.add'),
          position: 'right'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'cancel',
          clickEvent: () => this.deleteCarSelect(),
          text: '删除',
          position: 'right'
        },
        {
          compKey: 'btnKey7',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey8',
          size: 'small',
          name: 'importTemplate',
          icon: 'iconfont icon-importTemplate',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          position: 'upload'

        },
        {
          compKey: 'btnKey9',
          size: 'small',
          name: 'export',
          position: 'left',
          clickEvent: () => this.exportExcel111(api.exportCar, '车辆信息'), // 导出
          text: '导出'
        },
        {
          compKey: 'btnKey10',
          type: 'text',
          size: 'small',
          name: 'importTemplateDownload',
          icon: 'iconfont  icon-importTemplateDownload',
          click: () => this.templateDownload(),
          text: '模板下载',
          position: 'left'
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: 'VIN：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '门店编码：',
              codeField: 'belongDlrcode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '实施门店编码：',
              codeField: 'Dlrcode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '执行情况：',
              codeField: 'repairStatus',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '0', statusText: '未维修' },
                { statusId: '1', statusText: '已维修' }
              ],
              type: 'dropdownList',
              isMust: true
            }
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'vin',
              label: 'VIN'
            },
            {
              prop: 'belongDlrName',
              label: '所属门店名称'
            },
            {
              prop: 'belongDlrcode',
              label: '所属门店编码'
            },
            {
              prop: 'repairDlrName',
              label: '实施门店名称'
            },
            {
              prop: 'Dlrcode',
              label: '实施门店编码'
            },
            {
              prop: 'repairStatus',
              label: '执行情况'
            },
            {
              prop: 'repairDate',
              label: '维修时间'
            }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        vin: '',
        belongDlrcode: '',
        belongDlrName: '',
        Dlrcode: '',
        repairStatus: '',
        activityCode: '',
        activityId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        onCheckSelectChange: (selection) => {
          this.selectCar = selection
        }
      }
    }
  },

  methods: {
    // 重置
    reset() {
      this.formField.vin = ''
      this.formField.belongDlrcode = ''
      this.formField.Dlrcode = ''
      this.formField.repairStatus = ''
    },
    // 查询
    queryTable() {
      this.formField.activityCode = this.dataForForm.activityCode
      this.formField.activityId = this.dataForForm.activityId
      this.$requestAPI({
        apiUrl: api.queryQualityActivityInfoCar.APIUrl,
        variables: this.formField
      }).then(res => {
        this.$refs.multipleTable.list = res.rows
      })
    },

    // 车辆选择新增
    carAdd() {
      this.popupsVisibleCar = true
    },

    // 删除
    deleteCarSelect() {
      if (!this.selectCar.length) return this.$message('请先勾选删除数据！')
      for (const i of this.selectCar) {
        this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.filter(
          (item) => item !== i
        )
      }
      this.carDatas = this.$refs['multipleTable'].list
    },

    // 弹窗返回数据判断及转换字段
    returnCarData(returnData) {
      const carTableData = this.$refs.multipleTable.list
      for (let i = 0; i < carTableData.length; i++) {
        if (carTableData[i].vin === returnData.vin) {
          this.$message({
            message: '此条数据已添加！',
            duration: 1000
          })
          return
        }
      }
      returnData.belongDlrName = returnData.dlrName
      returnData.belongDlrcode = returnData.dlrCode
      this.$refs.multipleTable.list.push(returnData)
      this.carDatas = this.$refs.multipleTable.list
    },

    // 关闭弹窗
    close0() {
      this.popupsVisibleCar = false
    },

    // 导出
    exportExcel111(api, title) {
      exportExcel(this.formField, api.APIUrl, api.ServiceCode, title)
    },

    // 模板下载
    templateDownload() {
      this.$requestAPI({
        method: 'POST',
        variables: { dataType: 'excel' },
        apiUrl: api.carTemplateDownload.APIUrl
      }).then(res => {
        this.$utils.downloadFile(res, '导入模板下载.xlsx')
      })
    },

    // 导入
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url = api.qualityimportCar.APIUrl

      that
        .$requestUpload(url, param, {
          activityCode: this.dataForForm.activityCode
        })
        .then(response => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            if (!this.$refs.multipleTable.list.length) {
              this.$refs.multipleTable.list = response.rows
            } else {
              const vinCode = this.$refs.multipleTable.list.map(row => row['vin'])
              response.rows.forEach((element, index) => {
                if (!vinCode.includes(element['vin'])) {
                // 若数据不存在 则加入网格
                  this.$refs.multipleTable.list.push(element)
                } else {
                // 数据存在,替换
                  this.$refs['multipleTable'].list[
                    this.$refs['multipleTable'].list.findIndex(o => o['vin'] === element['vin'])
                  ] = element
                }
              })
            }
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch(_ => {})
    }
  }
}
</script>
